package com.wthink.hzgj.util.adapter

import androidx.databinding.BindingAdapter
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T : BaseViewHolder> : RecyclerView.Adapter<T>() {

    companion object {
        @JvmStatic
        @BindingAdapter("items")
        fun RecyclerView.bindItems(items: List<Any>) {
            adapter?.let {
                val adapter = adapter as BaseAdapter
                adapter.update(items)
            }
        }
    }

    open var items = emptyList<Any>()
        get

    var mItemClickListener: OnItemClickListener? = null

    open fun update(items: List<Any>) {
        this.items = items
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return this.items.size
    }

    override fun onBindViewHolder(holder: T, position: Int) {
        if (items.size > position) {
            holder.bind(items.get(position))
        }
        mItemClickListener?.let { listener ->
            holder.itemView.setOnClickListener {
                if (items.size > position) {
                    listener.onItemClick(items[position], position)
                }
            }
        }
    }
}

open class BaseViewHolder(val dataBinding: ViewDataBinding, val variableId: Int? = null) :
    RecyclerView.ViewHolder(dataBinding.root) {

    fun bind(value: Any?) {
        variableId?.let {
            dataBinding.setVariable(variableId, value)
            dataBinding.executePendingBindings()
        }
    }

}

interface OnItemClickListener {
    fun onItemClick(obj: Any, position: Int)
}